package com.jmcgg.scheduler;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;
import org.quartz.DateBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

/**
 * Servlet implementation class ScheduleServlet
 */
public class SchedulerInitServlet extends HttpServlet {
	private static final long serialVersionUID = -816178717878253238L;
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SchedulerInitServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SchedulerInitServlet() {
		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		logger.info("server start!");
		initScheduler(config);
	}

	protected void initScheduler(ServletConfig cfg) {
		try {

			SchedulerFactory sf = new StdSchedulerFactory();
			Scheduler scheduler = sf.getScheduler();
			// jobs can be scheduled before sched.start() has been called

			// get a "nice round" time a few seconds in the future...
			Date startTime = DateBuilder.nextGivenSecondDate(null, 15);

			// job will run indefinitely, every 1 minute
			JobDetail job = newJob(HeartBeatJob.class).withIdentity("heartBeatJob", "zsgh").build();

			SimpleTrigger trigger = newTrigger().withIdentity("heartBeatTrigger", "zsgh").startAt(startTime)
					.withSchedule(simpleSchedule().withIntervalInMinutes(1).repeatForever()).build();

			Date ft = scheduler.scheduleJob(job, trigger);
			logger.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount()
					+ " times, every " + trigger.getRepeatInterval() / 1000 + " seconds");

			// All of the jobs have been added to the scheduler, but none of the jobs
			// will run until the scheduler has been started
			scheduler.start();

			logger.info("------- Started Scheduler -----------------");
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
